package com.lhd.web.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lhd.po.*;
import com.lhd.service.BlogService;
import com.lhd.service.TagService;
import com.lhd.service.TypeService;
import com.lhd.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by limi on 2017/10/15.
 */
@Controller
@RequestMapping("/admin")
public class BlogController {

    private static final String INPUT = "admin/blogs-input";
    private static final String LIST = "admin/blogs";
    private static final String REDIRECT_LIST = "redirect:/admin/blogs";


    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;

    @GetMapping("/blogs")
    public String blogs(@RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                        BlogQuery blog, Model model) {
        model.addAttribute("types", typeService.listType());
        //model.addAttribute("page", blogService.listBlog(page, blog));


        //model.addAttribute("page",blogService.listTag(page));
        Long pageNum = blogService.countBlog();
        Long rem = pageNum % 10;

        List<Blog> blogs = blogService.listBlog(page, blog);
        for (Blog b:blogs){
            b.setType(typeService.getType(Long.valueOf(b.getTypeId())));
        }

        model.addAttribute("page",blogs);
        model.addAttribute("pageNum",pageNum/10 + (rem == 0 ? 0 : 1));
        model.addAttribute("curPage",page);
        model.addAttribute("preBoolean",page != 0);
        model.addAttribute("nexBoolean",page != ((pageNum/10 + (rem == 0 ? 0 : 1))-1));

        return LIST;
    }

    @PostMapping("/blogs/search")
    public String search(@RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                         BlogQuery blog, Model model) {
        Long pageNum = blogService.countBlogByQuery(blog);
        Long rem = pageNum % 10;
        List<Blog> blogs = blogService.listBlog(page, blog);
        for (Blog b:blogs){
            b.setType(typeService.getType(Long.valueOf(b.getTypeId())));
        }
        model.addAttribute("page",blogs);
        model.addAttribute("pageNum",pageNum/10 + (rem == 0 ? 0 : 1));
        model.addAttribute("curPage",page);
        model.addAttribute("preBoolean",page != 0);
        model.addAttribute("nexBoolean",page != ((pageNum/10 + (rem == 0 ? 0 : 1))-1));
        return "admin/blogs :: blogList";
    }


    @GetMapping("/blogs/input")
    public String input(Model model) {
        setTypeAndTag(model);
        model.addAttribute("blog", new Blog());
        return INPUT;
    }

    private void setTypeAndTag(Model model) {
        model.addAttribute("types", typeService.listType());
        model.addAttribute("tags", tagService.listTag());
    }


    @GetMapping("/blogs/{id}/input")
    public String editInput(@PathVariable Long id, Model model) {
        setTypeAndTag(model);
        Blog blog = blogService.getBlog(id);
        model.addAttribute("blog",blog);
        return INPUT;
    }

    @PostMapping("/blogs")
    public String post(Blog blog, RedirectAttributes attributes, HttpSession session) {
        blog.setUser((User) session.getAttribute("user"));
        blog.setUserId(((User)session.getAttribute("user")).getId());
        blog.setTypeId(blog.getType().getId());
        blog.setViews(0);
        List<Long> tagIds = tagService.convertToList(blog.getTagIds());
        Integer b;
        blog.setUpdateTime(new Date());
        if (blog.isPublished()){   //发布动作
            if (blog.getId() == null){   //说明是新博客发布
                blog.setId(blogService.getMaxBlogId()+1);
                blog.setCreateTime(new Date());
                b = blogService.saveBlog(blog);
                tagService.createBlogIdAndTagIds(blog.getId(),tagIds); //保存blogid tagid 关系表
            }{      //说明是已保存博客发布 或者 已发布博客修改后重新发布
                //删除blogid对应的tagid
                tagService.clearBlogIdAndTagId(blog.getId());
                //添加blohgid对应的tagid
                tagService.createBlogIdAndTagIds(blog.getId(),tagIds);
                b = blogService.updateBlog(blog.getId(),blog);
            }
        }else {   //保存动作
            if (blogService.getBlog(blog.getId()) == null){  //说明此时数据库中无此博客，则为新建博客保存
                blog.setId(blogService.getMaxBlogId()+1);
                blog.setCreateTime(new Date());
                b = blogService.saveBlog(blog);
            }else {  //说明数据库中已有此博客信息，为旧博客
                Blog blogInner = blogService.getBlog(blog.getId());
                if (blogInner.isPublished()){   //说明是已发布旧博客修改后保存
                    tagService.clearBlogIdAndTagId(blog.getId());
                    b = blogService.updateBlog(blog.getId(),blog);
                }else {  //说明是未发布旧博客修改后保存
                    b = blogService.updateBlog(blog.getId(),blog);
                }
            }
        }
        if (b == 0) {
            attributes.addFlashAttribute("message", "操作失败");
        } else {
            attributes.addFlashAttribute("message", "操作成功");
        }
        return REDIRECT_LIST;
    }


    @GetMapping("/blogs/{id}/delete")
    public String delete(@PathVariable Long id,RedirectAttributes attributes) {
        blogService.deleteBlog(id);
        attributes.addFlashAttribute("message", "删除成功");
        return REDIRECT_LIST;
    }


    public static void main(String[] args) {

    }
}
